package com.hunlian.makelove.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.utils.FileUtils;
import com.blankj.utilcode.utils.StringUtils;
import com.bumptech.glide.Glide;
import com.hunlian.makelove.AppApplication;
import com.hunlian.makelove.R;
import com.hunlian.makelove.TakeCameraOrAlbum;
import com.hunlian.makelove.common.AppConfig;
import com.hunlian.makelove.common.ContextUtils;
import com.hunlian.makelove.common.Printout;
import com.hunlian.makelove.net.HttpPostUploadUtil;
import com.hunlian.makelove.net.IServiceReturnProcess;
import com.hunlian.makelove.net.ServiceInterfaceDef;
import com.hunlian.makelove.tools.MyToast;
import com.hunlian.makelove.tuyaimage.TuyaActivity;
import com.yuyh.library.imgsel.ImageLoader;
import com.yuyh.library.imgsel.ImgSelActivity;
import com.yuyh.library.imgsel.ImgSelConfig;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 学历提交审核
 * Created by zealjiang on 2017/5/4 17:11.
 * Email: zealjiang@126.com
 */

public class FurtherInfoSubmitActivity extends BaseActivity {

    @BindView(R.id.back)
    ImageButton ibBack;
    @BindView(R.id.title)
    TextView tvTitle;
    @BindView(R.id.iv_edu_example)
    ImageView ivEduExample;
    @BindView(R.id.iv_education_certificate)
    ImageView ivEduCer;
    @BindView(R.id.btnSubmit)
    Button btnSubmit;

    private FurtherInfoSubmitActivity activity;
    private TakeCameraOrAlbum takeCameraOrAlbum;
    private String mPicDir;//学历图片保存的目录
    private final String StrEducation = "edu";
    private static final int REQUEST_CODE_PHOTO = 111;
    private static final int REQUEST_CODE_TUYA = 112;
    private static final int REQUEST_CODE_BIG_PHOTO = 113;
    private String eduPath;
    private String bpath = "HLW_Pics/person";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_further_info_submit);
        ButterKnife.bind(this);
        activity = this;

        tvTitle.setText("学历审核");
        takeCameraOrAlbum = new TakeCameraOrAlbum();
        //从资源id中获取图片文件夹地址
        mPicDir = ContextUtils.getPicDirName(this, bpath);
    }

    @OnClick({R.id.back,R.id.iv_edu_example,R.id.iv_education_certificate,R.id.btnSubmit})
    public void onClick(View v){
        Intent intent;
        switch (v.getId()){
            case R.id.back:
                activity.finish();
            break;
            case R.id.iv_edu_example:
                intent = new Intent(activity, SpaceImageDetailActivity.class);
                intent.putExtra("url","res");
                intent.putExtra("resId",R.drawable.edu_example);
                startActivity(intent);
                overridePendingTransition(0, 0);
                break;
            case R.id.iv_education_certificate:
                if(TextUtils.isEmpty(eduPath)){
                    singleSelect();
                }else if(!new File(eduPath).exists()){
                    //删除空的图片
                    deleteEduFile(eduPath);
                    eduPath = "";
                    singleSelect();
                }else {
                    intent = new Intent(activity, SpaceImageDetailActivity.class);
                    intent.putExtra("url",eduPath);
                    intent.putExtra("canModify",true);
                    startActivityForResult(intent,REQUEST_CODE_BIG_PHOTO);
                    overridePendingTransition(0, 0);
                }
                break;
            case R.id.btnSubmit:
                //提交
                requestSubmit(eduPath);
                break;
        }
    }


    private ImageLoader loader = new ImageLoader() {
        @Override
        public void displayImage(Context context, String path, ImageView imageView) {
            Glide.with(context).load(path).into(imageView);
        }
    };

    public void singleSelect() {
        ImgSelConfig config = new ImgSelConfig.Builder(activity,loader)
                // 是否多选
                .multiSelect(false)
                // 是否记住上次选中记录, 仅当multiSelect为true的时候配置，默认为true
                .rememberSelected(false)
                // 确定按钮背景色
                .btnBgColor(Color.GRAY)
                // 确定按钮文字颜色
                .btnTextColor(Color.BLUE)
                // 使用沉浸式状态栏
                .statusBarColor(Color.parseColor("#3F51B5"))
                // 返回图标ResId
                //.backResId(android.support.v7.appcompat.R.drawable.abc_ic_ab_back_mtrl_am_alpha)
                .title("图片")
                .titleColor(Color.WHITE)
                .titleBgColor(Color.parseColor("#3F51B5"))
                .cropSize(1, 1, 200, 200)
                .needCrop(false)
                // 第一个是否显示相机
                .needCamera(true)
                // 最大选择图片数量
                .maxNum(9)
                .build();

        ImgSelActivity.startActivity(this, config, REQUEST_CODE_PHOTO);
    }

    private void startTuyaActivity(int requestCode, String srcPath,String savePath) {
        //编辑图片
        Intent intent = new Intent(activity, TuyaActivity.class);
        intent.putExtra("path", srcPath);
        intent.putExtra("savePath", savePath);
        activity.startActivityForResult(intent, requestCode);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case REQUEST_CODE_PHOTO:
                if (resultCode == RESULT_OK && data != null) {
                    List<String> pathList = data.getStringArrayListExtra(ImgSelActivity.INTENT_RESULT);
                    String showPath = pathList.get(0);

                    eduPath = mPicDir+System.currentTimeMillis()+StrEducation+".jpg";
                    //编辑图片
                    startTuyaActivity(REQUEST_CODE_TUYA, showPath,eduPath);
                }
                break;
            case REQUEST_CODE_TUYA:
                if(resultCode == RESULT_OK){
                    //加载并显示图片
                    takeCameraOrAlbum.loadShowIdentity(activity, ivEduCer, eduPath, false);
                }else{
                    //删除旧的图片
                    deleteEduFile(eduPath);
                    eduPath = "";
                }

                break;
            case REQUEST_CODE_BIG_PHOTO:
                if(data != null){
                    boolean isModify = data.getBooleanExtra("modify",false);
                    if(isModify){
                        singleSelect();
                    }
                }
                break;
        }

    }

    private void requestSubmit(String path){
        if(StringUtils.isEmpty(path)){
            MyToast.showShort("请先上传图片再提交");
            return;
        }
        File imgFile = new File(path);
        if(!imgFile.exists()){
            MyToast.showShort("图片出错，请重新选择上传");
            return;
        }

        if (!AppApplication.networkAvailable) {
            MyToast.showShort("没有网络");
            return;
        }

        Map<String, String> textMap = new HashMap<String, String>();
        textMap.put("functionId", ServiceInterfaceDef.FUNC_ID_EDUCATION);
        textMap.put("userId", AppConfig.getInstance().getLoginedUserId());
        textMap.put("time1", AppApplication.SIGNMD5);

        Map<String, String> fileMap = new HashMap<String, String>();
        fileMap.put("eduFile", path);

        createProgressDialog(activity);
        progressDialog.show();

        HttpPostUploadUtil.doPost(ServiceInterfaceDef.SERVICE_URL, textMap, fileMap,
                new IServiceReturnProcess() {
                    @Override
                    public void process(String serviceReturn) {
                        if (progressDialog != null && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                        Printout.println("上传学历反馈" + serviceReturn);

                        if (TextUtils.isEmpty(serviceReturn)) {
                            return;
                        }
                        try {
                            JSONObject obj = new JSONObject(serviceReturn);
                            String status = obj.getString("status");
                            if (status.equals("1")) {
                                Toast.makeText(activity, "学历上传成功", Toast.LENGTH_SHORT).show();
                                //删除学历文件夹
                                FileUtils.deleteDir(mPicDir);
                                AppConfig.eduState = 2;
                                activity.setResult(RESULT_OK);
                                activity.finish();
                            } else {
                                MyToast.showShort(obj.getString("message"));
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                });
    }

    private void deleteEduFile(String eduPath){
        if(TextUtils.isEmpty(eduPath)){
            return;
        }
        //删除图片
        ContextUtils.DeleteFile(new File(eduPath));
        sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File(eduPath))));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //删除图片
        deleteEduFile(eduPath);
    }
}
